"""
简化的视频分析 API 路由
"""
from fastapi import APIRouter, HTTPException
from typing import Optional
import logging

from app.models.video import SimpleVideoAnalysisRequest, SimpleVideoAnalysisResponse
from app.services.video_analysis import video_service

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/video", tags=["视频分析"])

@router.post("/analyze-direct", response_model=SimpleVideoAnalysisResponse, summary="视频分析")
async def analyze_video_direct(request: SimpleVideoAnalysisRequest):
    """
    分析视频内容 - 支持多轮对话
    
    参数:
    - **video_path**: 视频文件路径（必填）
    - **questions**: 问题列表，按ID顺序执行，支持多轮对话（默认：[{id:1, question:"Describe video in detail"}]）
    - **subtitle**: 可选的字幕内容，作为上下文提供给模型（默认：None）
    - **max_num_frames**: 最大帧数（默认：60）
    """
    try:
        logger.info(f"收到视频分析请求 - Video: {request.video_path}")
        logger.info(f"Questions: {[f'{q.id}: {q.question}' for q in request.questions]}")
        logger.info(f"Max frames: {request.max_num_frames}")
        
        # 调用 VideoChat-Flash 进行多轮分析
        result = await video_service.analyze_video_multi_turn(
            video_path=request.video_path,
            questions=request.questions,
            subtitle=request.subtitle,
            max_num_frames=request.max_num_frames
        )
        
        return SimpleVideoAnalysisResponse(
            answers=result["answers"],
            processing_time=result["processing_time"],
            frames_processed=result["frames_processed"],
            total_questions=result["total_questions"]
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"视频分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"视频分析失败: {str(e)}")

# 保留健康检查端点
@router.get("/health", summary="服务健康检查")
async def health_check():
    """
    检查视频分析服务状态
    """
    try:
        model_ready = video_service.is_model_ready()
        return {
            "status": "healthy" if model_ready else "model_not_ready",
            "model_ready": model_ready,
            "service": "video_analysis",
            "model": "VideoChat-Flash-Qwen2_5-2B"
        }
    except Exception as e:
        logger.error(f"健康检查失败: {str(e)}")
        return {
            "status": "unhealthy",
            "model_ready": False,
            "error": str(e)
        }